#!/usr/bin/env Rscript
################################
## Generalization Error
## estimation for fraud paper
## Block bootstrap, context 
## features 
################################




# Flag to send job to cluster or 
# run in a regular computer (still in parallel,
# using MPI backend)
PegasusRun  <- commandArgs()

if(PegasusRun){
  system("bsub < GenErrorBootContext.job")
}else{
  #!/usr/bin/env Rscript
  
  ## Load libraries on all cores
  library(plyr)
  library(foreach)
  library(doMPI)
  
  ## Seed RNG
  set.seed(831213)
  
  ## Start cluster & worker loop
  cl  <- startMPIcluster()
  registerDoMPI(cl)
  
  ## Load libraries on master
  library(BayesTree)
  library(glmnet)
  
  
  ## Load auxiliary functions
  source("./GenErrorAuxFunc.R")
  
  ## Get processed data
  load("./FullData.RData")
  
  
  ## Estimate bootstrap generalization errors
  ## Set nr. of bootstrap samples
  n.boot.samp <- 150
  
  ## Get best parameters from parameter sweep
  bestParams <- read.csv("./BSParamSweep.csv"
                         ,nrows=1
  )[,1:6]
  bartParams  <- expand.grid(k=bestParams$k
                             ,pow=bestParams$pow
                             ,base=bestParams$base
                             ,sigdf=bestParams$sigdf
                             ,sigquant=bestParams$sigquant
                             ,ntree=bestParams$ntree
                             ,sampind=1:n.boot.samp
                             ,burnin=50e3
                             ,niter=5e3
                             ,keepevery=10)
  bartParams  <- as.matrix(bartParams)
  
  ## Estimate generalization errors
  ## For context-only model
  ## using 150 bootstrap block samples
  context.errors.boot  <- err.generator(n.boot.samp
                                        ,bartParams
                                        ,all.data$fDataInform
                                        ,all.data$countries.inform
                                        ,parallel=TRUE)
  
  
  ## Save results
  save(context.errors.boot
       ,file="./GenErrorsBootContext.RData")
  
  closeCluster(cl)
  mpi.finalize()
}